package com.cct.digitalarchapi.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cct.digitalarchapi.common.CommonUtil;
import com.cct.digitalarchapi.common.Constant;
import com.cct.digitalarchapi.common.EncryptUtil;
import com.cct.digitalarchapi.common.Response;
import com.cct.digitalarchapi.dao.MessageMapper;
import com.cct.digitalarchapi.dao.RoleMapper;
import com.cct.digitalarchapi.dao.RootListMapper;
import com.cct.digitalarchapi.dao.StaffListMapper;
import com.cct.digitalarchapi.pojo.Message;
import com.cct.digitalarchapi.pojo.RootList;
import com.cct.digitalarchapi.pojo.StaffList;
import com.cct.digitalarchapi.pojo.vo.AllRoleMenuVo;
import com.cct.digitalarchapi.pojo.vo.RootVo;
import com.cct.digitalarchapi.pojo.vo.SystemInfoVo;
import com.cct.digitalarchapi.pojo.vo.UserVo;
import com.cct.digitalarchapi.service.RoleAndMenuService;
import com.cct.digitalarchapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.cct.digitalarchapi.common.LinuxStateForShell.disposeFilesSystem;
import static com.cct.digitalarchapi.common.LinuxStateForShell.runDistanceShell;
import static com.cct.digitalarchapi.common.LinuxStateForShell.runLocalShell;

/**
 * @FileName ArchCategoryServiceImpl
 * @Description 档案分类实现类
 * @Author Created by chenmingzhe
 * @Date 2023/11/19
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RootListMapper rootListMapper;
    @Autowired
    private StaffListMapper staffListMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EncryptUtil encryptUtil;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private Constant constant;
    @Autowired
    private RoleAndMenuService roleAndMenuService;

    @Override
    public Response loginByManager(String username, String psswd) {
        try {
            String num = rootListMapper.qryHaveManager(username);
            String uesrNum=staffListMapper.qryHaveUser(username);
            if ("0".equals(num)&&"0".equals(uesrNum)) {
                return Response.bad("登陆失败，用户名或登录密码错误！");
            } else if("1".equals(num)) {
                RootVo rootVo=new RootVo();
                RootList manager = rootListMapper.qryManager(username);
                if (manager.getPasswd().equals(psswd)) {
                    manager.setPasswd(null);
                    BeanUtils.copyProperties(manager, rootVo);
                    rootVo.setIsRoot("1");
                    rootVo.setRoleId(rootVo.getRootType());
                    List<AllRoleMenuVo> res=roleAndMenuService.getRoleMenu(rootVo.getRootType(),"0");
                    rootVo.setRes(res);
                    if(rootVo.getRootType()==9){
                        rootVo.setRoleName("超级管理员");
                    }else{
                        String roleName=roleMapper.getRoleNameById(rootVo.getRoleId());
                        rootVo.setRoleName(roleName);
                    }
                    return Response.success(rootVo);
                } else {
                    return Response.bad("登陆失败，用户名或登录密码错误！");
                }
            }else{
                UserVo userVo=new UserVo();
                StaffList user = staffListMapper.qryUser(username);
                if (user.getPasswd().equals(psswd)) {
                    user.setPasswd(null);
                    BeanUtils.copyProperties(user, userVo);
                    userVo.setIsRoot("0");
                    userVo.setRoleId(userVo.getRoleId());
                    List<AllRoleMenuVo> res=roleAndMenuService.getRoleMenu(userVo.getRoleId(),userVo.getIsRoot());
                    userVo.setRes(res);
                    String roleName=roleMapper.getRoleNameById(userVo.getRoleId());
                    userVo.setRoleName(roleName);
                    return Response.success(userVo);
                } else {
                    return Response.bad("登陆失败，用户名或登录密码错误！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("登陆失败：{}", e.getMessage());
            return Response.error("登陆失败");
        }
    }

    @Override
    public Response loginByUser(String staffCode, String psswd) {
        try {
            String num = staffListMapper.qryHaveUser(staffCode);
            if ("0".equals(num)) {
                return Response.bad("登陆失败，用户名或登录密码错误！");
            } else {
                StaffList user = staffListMapper.qryUser(staffCode);
                if (user.getPasswd().equals(psswd)) {
                    user.setPasswd(null);
                    return Response.success(user);
                } else {
                    return Response.bad("登陆失败，用户名或登录密码错误！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("登陆失败：{}", e.getMessage());
            return Response.error("登陆失败");
        }
    }

    @Override
    public Response addManager(RootList rootList) {
        try {
            String num = rootListMapper.qryHaveManager(rootList.getUsername());
            if ("1".equals(num)) {
                return Response.bad("档案管理人员已存在！");
            }
            if ("root".equals(rootList.getUsername())) {
                rootList.setRootType(9);
            } else {
                rootList.setRootType(rootList.getRootType());
            }
            rootList.setPasswd(encryptUtil.encryption("adc_123"));
            rootListMapper.addManager(rootList);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加档案管理人员失败：{}", e.getMessage());
            return Response.error("添加档案管理人员失败");
        }
    }

    @Override
    public Response addUser(StaffList staffList) {
        try {
            String num = staffListMapper.qryHaveUser(staffList.getStaffCode());
            if ("1".equals(num)) {
                return Response.bad("员工已存在！");
            }
            staffList.setStaffState(0);
            staffList.setPasswd(encryptUtil.encryption("adc_123"));
            staffListMapper.addUser(staffList);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加员工失败：{}", e.getMessage());
            return Response.error("添加员工失败");
        }
    }

    @Override
    public Response deleteManager(String username) {
        try {
            if ("root".equals(username)) {
                return Response.bad("root用户不可删除！");
            }
            rootListMapper.deleteManager(username);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除档案管理人员失败：{}", e.getMessage());
            return Response.error("删除档案管理人员失败");
        }
    }

    @Override
    public Response deleteUser(int staffId) {
        try {
            staffListMapper.deleteUser(staffId);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除员工失败：{}", e.getMessage());
            return Response.error("删除员工失败");
        }
    }

    @Override
    public Response qryAllManager(int pageNum, int pageSize) {
        try {
            Page<RootList> page=new Page<>(pageNum,pageSize);
            rootListMapper.qryAllManager(page);
            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询所有管理员失败：{}", e.getMessage());
            return Response.error("查询所有管理员失败");
        }
    }

    @Override
    public Response qryUserByDept(String archDeptCode,int pageNum,int pageSize,String staffName,String staffCode) {
        try {
            Page<StaffList> page=new Page<>(pageNum,pageSize);
            staffListMapper.qryUserByDept(page,archDeptCode,staffName,staffCode);
            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据部门查询所有的员工失败：{}", e.getMessage());
            return Response.error("根据部门查询所有的员工失败");
        }
    }

    @Override
    public Response updatePasswd(String username, String oldPasswd, String newPasswd, String type) {
        try {
            if ("1".equals(type)) {
                //管理员
                RootList rootList = rootListMapper.qryManager(username);
                if (!oldPasswd.equals(rootList.getPasswd())) {
                    return Response.bad("输入的旧密码错误");
                } else {
                    rootListMapper.updatePasswd(username, newPasswd);
                }
            } else if ("2".equals(type)) {
                //员工
                StaffList staffList = staffListMapper.qryUser(username);
                if (!oldPasswd.equals(staffList.getPasswd())) {
                    return Response.bad("输入的旧密码错误");
                } else {
                    staffListMapper.updatePasswd(username, newPasswd);
                }
            } else {
                return Response.bad("type传值错误");
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新密码失败：{}", e.getMessage());
            return Response.error("更新密码失败");
        }
    }

    @Override
    public Response updateManager(RootList rootList) {
        try {
            rootListMapper.updateManager(rootList);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新档案管理员失败：{}", e.getMessage());
            return Response.error("更新档案管理员失败");
        }
    }

    @Override
    public Response updateUser(StaffList staffList) {
        try {
            staffListMapper.updateUser(staffList);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新员工信息失败：{}", e.getMessage());
            return Response.error("更新员工信息失败");
        }
    }

    @Override
    public Response resetPasswd(String username, String type) {
        try {
            String passwd=encryptUtil.encryption("adc_123");
            if ("1".equals(type)) {
                rootListMapper.updatePasswd(username, passwd);
            } else if ("2".equals(type)) {
                staffListMapper.updatePasswd(username, passwd);
            } else {
                return Response.bad("type传值错误");
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("重置密码失败：{}", e.getMessage());
            return Response.error("重置密码失败");
        }
    }

    @Override
    public Response getStaffCode() {
        try {
            StaffList staffList=staffListMapper.getLastStaff();
            int num=Integer.parseInt(staffList.getStaffCode());
            return Response.success(String.format("%04d",num+1));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取员工编号失败：{}", e.getMessage());
            return Response.error("获取员工编号失败");
        }
    }

    @Override
    public Response getMessageByUser(String username, int state,int pageNum,int pageSize,int type) {
        try {

            Page<Message> page=new Page<>(pageNum,pageSize);
            if(type==1){
                if(state==-1){
                    messageMapper.getAllMessgaeByManage(page,username);
                }else{
                    messageMapper.getStateMessgaeByManage(page,username,state);
                }
            }else{
                if(state==-1){
                    messageMapper.getAllMessgaeByUser(page,username);
                }else{
                    messageMapper.getStateMessgaeByUser(page,username,state);
                }
            }

            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询用户的消息失败：{}", e.getMessage());
            return Response.error("查询用户的消息失败");
        }
    }

    @Override
    public Response updateMessageState(int messId, int state) {
        try {
            messageMapper.updateState(messId,state);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新消息的状态失败：{}", e.getMessage());
            return Response.error("更新消息的状态失败");
        }
    }

    @Override
    public Response getSystemInfo() {
        try {
            SystemInfoVo systemInfoVo=new SystemInfoVo();
            String storePath=constant.getUploadPath();
            systemInfoVo.setArchMainPath(storePath+"Archives");
            systemInfoVo.setKnowPath(storePath+"Know");
            systemInfoVo.setNowStorePath(storePath);
            List<String> list = Arrays.asList(constant.getIp().split("/"));
            String serverIp=(Arrays.asList(list.get(2).split(":"))).get(0);
            systemInfoVo.setServerIp(serverIp);
            systemInfoVo.setMaxFile(constant.getMaxFileSie());
            String[] commands = {"df -hl"};
            Map<String, String> result = runLocalShell(commands);
            List<String> res=disposeFilesSystem(result.get("df -hl"));
            systemInfoVo.setAllSpace(res.get(0));
            systemInfoVo.setUseSpace(res.get(1));
            systemInfoVo.setLeftSpace(res.get(2));
            systemInfoVo.setColor("red");
            systemInfoVo.setSize("10");
            return Response.success(systemInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询系统信息失败：{}", e.getMessage());
            return Response.error("查询系统信息失败");
        }
    }

    @Override
    public Response uploadWaterMark(MultipartFile file) {
        String markPath=constant.getUploadPath()+"WaterMark/waterMark.png";
        File dest = new File(markPath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传水印失败：{}", e.getMessage());
            return Response.error("上传水印失败");
        }
        return Response.success("上传成功");
    }

}
